package com.sangeng.filter;

import com.sangeng.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
@Component
public class MenuFilter implements FilterInvocationSecurityMetadataSource {
    @Resource
    private MenuMapper menuMapper;

    /**
     * 根据参数转化为 FilterInvocation 类型
     * 获取当前请求的 requestUrl
     * 根据 requestUrl 查询数据库 获取当前路经所需的权限列表
     * 封装权限列表关键字段到 Collection<ConfigAttribute>
     * 如果未获取到权限信息则默认为登录权限（不需要校验的/白名单路经）
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        HashSet<ConfigAttribute> set= new HashSet<>();
        FilterInvocation filterInvocation = (FilterInvocation) object;
        String requestUrl = filterInvocation.getRequestUrl();
        System.out.println("=======================>>>请求路经："+requestUrl);
        //根据路经获取权限列表
        List<String> allPath = menuMapper.selectPermsByPath(requestUrl);
        //封装权限列表
        if (!CollectionUtils.isEmpty(allPath)){
            allPath.forEach(path->{
                set.add(new SecurityConfig(path));
            });
        }
        //权限列表为空 未配置权限的都是白名单
        if (ObjectUtils.isEmpty(set)){
            return SecurityConfig.createList("ROLE_LOGIN");
        }
        //返回权限列表
        return set;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
